<?php

namespace StarCloud\Library;

use Hashids\Hashids;

class Tool
{
    public static function getChildDomainPre()
    {
        $url = "http://" . $_SERVER ['HTTP_HOST'] . $_SERVER['PHP_SELF'];
        preg_match("#http://(.*?)\.#i", $url, $match);

        echo $match[1];
    }

    public static function smsCode()
    {
        return mt_rand(100000, 999999);
    }

    public static function generateUniqCode($uniqNumber, $length = 6)
    {
        $salt = 'p4f28Gc6R57nk5';
        $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';

        $hashids = new Hashids($salt, $length, $alphabet);

        return $hashids->encode($uniqNumber);
    }

    public static function getIp(): string
    {
        $PHP_IP = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $PHP_IP = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $PHP_IP = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $PHP_IP = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $PHP_IP = $_SERVER['REMOTE_ADDR'];
        }

        \Phalcon\Di::getDefault()->get('logger')->info("ips is :" . $PHP_IP);

        preg_match("/[\d\.]{7,15}/", $PHP_IP, $ipmatches);
        $PHP_IP = $ipmatches && count($ipmatches) > 0 && $ipmatches[0] ? $ipmatches[0] : 'unknown';

        return $PHP_IP != 'unknown' ? $PHP_IP : '127.0.0.1';
    }

    public static function getUserAgent()
    {
        return  $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    }

    public static function treeData($data, $pid = 0)
    {
        $result = null;
        foreach ($data as $v) {
            if ($v['pid'] == $pid) {
                $v['children'] = self::treeData($data, $v['id']);
                $result[] = $v;
            }
        }
        return $result;
    }

    public static function getRandStr($length)
    {
        //字符组合
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    public static function gmtIso8601($time)
    {
        return str_replace('+00:00', '.000Z', gmdate('c', $time));
    }

    public static function downloadUrlFile($urlFilePath)
    {
        if (!file_exists($urlFilePath)) {
            $exts = explode('.', $urlFilePath);
            $alisPathFile = FILE_STATIC_PATH . DS . md5($urlFilePath) . '.' . array_pop($exts);
            file_put_contents($alisPathFile, file_get_contents($urlFilePath));
            $urlFilePath = $alisPathFile;
        }

        return $urlFilePath;
    }

    public static function getUrlBaseName($url)
    {
        $pathInfo = pathinfo(parse_url($url, PHP_URL_PATH));

        return $pathInfo['basename'];
    }

    public static function timeHis($time)
    {
        if ($time >3600) {
            $hours =intval($time/3600);
            $minutes = $time % 3600;
            $times = $hours.":".gmstrftime('%M:%S', $minutes);
        } else {
            $times = gmstrftime('%H:%M:%S', $time);
        }
        return $times;
    }

    public static function getDayArr($day)
    {
        $days = [];
        $weekarray=["日","一","二","三","四","五","六"];

        for ($i = 0; $i < $day; $i++) {
            $date = date('Y-m-d', strtotime("+ $i day"));
            $days[] = [
                'date' => $date,
                'week' => '周'.$weekarray[date("w", strtotime($date))],
            ];
        }

        return $days;
    }

    public static function time_ago($agoTime)
    {
        $agoTime = (int)$agoTime;
        $time = time() - $agoTime;
        if ($time >= 31104000) { // N年前
            $num = (int)($time / 31104000);
            return $num . '年前';
        }
        if ($time >= 2592000) { // N⽉前
            $num = (int)($time / 2592000);
            return $num . '⽉前';
        }
        if ($time >= 86400) { // N天前
            $num = (int)($time / 86400);
            return $num . '天前';
        }
        if ($time >= 3600) { // N⼩时前
            $num = (int)($time / 3600);
            return $num . '⼩时前';
        }
        if ($time > 60) { // N分钟前
            $num = (int)($time / 60);
            return $num . '分钟前';
        }
        return '刚刚';
    }
}
